<?php
namespace App\Admin\Controllers\Purchase;

use App\Admin\Ajax\Purchase\OrderAjax;
use App\Models\Inventory\StorageDetail;
use App\Models\Sys\Logs;
use App\Models\Basics\SettlementMethod;
use App\Models\Purchase\PurchaseOrder;
use App\Util\User;
use Encore\Admin\Admin;
use Encore\Admin\Controllers\AdminController;
use App\Models\Basics\Supplier;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Support\Facades\Request;
class OrderController extends AdminController{

    protected $title = '采购单';

    protected function grid()
    {
        $grid = new Grid(new PurchaseOrder());
        $grid->model()->newQuery()
            ->orderBy('status', 'ASC')
            ->orderBy('id', 'DESC');
        $grid->column('purchase_no','订单号');
        $grid->column('pu_user_id','采购人')->display(function ($value){
            return User::getUsernameById($value);
        });
        $grid->column('status','下单状态')->using(PurchaseOrder::getStatus());
        $grid->column('supplier.name','供应商');
        $grid->column('received_status','收货状态')->display(function ($value){
            return PurchaseOrder::$_receivedStatus[$value];
        });
        $grid->column('settlement_method.settlement_method','结算方式');
        $grid->column('remarks','备注')->style('max-width:200px');
        $grid->column('order_at','下单时间');
        Admin::script($this->_script());
        $grid->column('操作')->view('purchase.order.action');
        $grid->disableActions();
        $grid->disableCreateButton();
        $grid->disableExport();
        $grid->disableRowSelector();
        $grid->filter(function($filter){
            $filter->column(1/2, function ($filter) {
                $filter->equal('purchase_no','订单号');
                $filter->equal('supplier_id','供应商')->select(Supplier::options());
                $filter->where(function ($query) {
                    $query->whereHas('order_detail.sku', function ($query) {
                        $query->where('psku_code', 'like', "%{$this->input}%")
                            ->orWhere('psku_cn', 'like', "%{$this->input}%");
                    });
                }, 'SKU')->placeholder('模糊查询SKU，名称');
            });
            $filter->column(1/2, function ($filter) {
                $filter->equal('status','下单状态')->select(PurchaseOrder::$_status);
                $filter->equal('received_status','收货状态')->select(PurchaseOrder::$_receivedStatus);
                $filter->between('order_at', '下单日期')->date();
            });
        });
        return $grid;
    }

    protected function _script()
    {
        $token = csrf_token();

        return <<<EOT
var _ajaxConfirm = function(action,param,resolve){
    $.ajax({
        method: 'post',
        url: '/xqc/purchase/order-ajax',
        data: {
            _token: "{$token}",
            action: action,
            param: param
        },
        success: function (data) {
            resolve(data);
        }
    });
};
//关闭
$('.grid-check-close').unbind('click').click(function(e) {
    e.preventDefault();
    var id = $(this).data('id');
    swal({
        title: "确定关闭？",
        text: "确定要关闭此单吗？",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        showLoaderOnConfirm: true,
        cancelButtonText: "取消",
        preConfirm: function() {
            return new Promise(function(resolve) {
                _ajaxConfirm('purClose',id,resolve)
            });
        }
    }).then(function(result) {
        var data = result.value;
        if (typeof data === 'object') {
            if (data.status) {
                toastr.success('提交成功 !');
                $.pjax.reload('#pjax-container');
            } else {
                swal(data.message, '', 'error');
            }
        }
    });
});
EOT;
    }

    public function edit($id, Content $content)
    {
        $purchase = PurchaseOrder::query()->findOrFail($id);
        $orderNum = 0; //采购数量
        $orderAmount = 0; //采购金额
        foreach ($purchase->order_detail as $detail){
            $orderNum += $detail->order_num;
            $orderAmount += $detail->order_num * $detail->supplier_price;
        }
        //结算方式
        $settlementMethodOptions = editableSourceJsonOption(SettlementMethod::options(['status' => 1]));

        //国内收货入库记录
        $sDetail = StorageDetail::query()->where('order_no',$purchase->purchase_no)->get()->sortBy('psku_id');
        return $content
            ->title($this->title())
            ->description($this->description['edit'] ?? trans('admin.edit'))
            ->body(view('purchase.order-edit.index', compact('id','purchase','settlementMethodOptions','sDetail','orderNum','orderAmount')));
    }

    public function update($id)
    {
        list($model,$name) = explode('-',Request::get('name'));
        $new = Request::get('value');
        $re = (PurchaseOrder::$_model[$model])::find($id);
        if($name == 'supplier_price'){
            $old = $re->supplier_price;
            $temp = $old - $new;
            $re->unit_price -= $temp;
        }
        $re->{$name} = $new;
        $re->save();
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new OrderAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    public function modal(){
        $action = request('action');
        $param = request('param');
        $modal = new OrderAjax();
        return $param ? call_user_func([$modal,$action],$param) : call_user_func([$modal,$action]);
    }

    /**
     * 查看/明细
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    protected function detail($id)
    {
        $purchase = PurchaseOrder::query()->findOrFail($id);
        $orderNum = 0;
        $orderAmount = 0;
        foreach ($purchase->order_detail as $detail){
            $orderNum += $detail->order_num;
            $orderAmount += $detail->order_num * $detail->supplier_price;
        }

        //国内收货入库记录
        $sDetail = StorageDetail::query()->where('order_no',$purchase->purchase_no)->get()->sortBy('psku_id');

        //采购日志
        $logs = Logs::getLogs('purchase',$id);
        return view('purchase.order-detail.index', compact('id','purchase','sDetail','orderNum','orderAmount','logs'));
    }

}
